<template>
	<div>
		<!-- v-bind=“options” 相当于把options对象里面的属性，一个一个拆出来绑定 -->
		<el-form ref="formInstance" :model="formData" v-bind="options">
			<el-row :gutter="10">
				<el-col :span="(item as any).col.span" v-for="item in rules" :key="(item as any).field">
					<el-form-item :label="(item as any).label" :prop="(item as any).field" :rules="(item as any).validate">
						<el-input
							v-if="(item as any).type === 'input'"
							v-model="formData[(item as any).field]"
							v-bind="(item as any).props"
							v-on="(item as any).on"
							:input-style="(item as any).style"
						></el-input>
						<el-select
							v-if="(item as any).type === 'select'"
							v-model="formData[(item as any).field]"
							v-bind="(item as any).props"
							:style="(item as any).style"
						>
							<el-option v-for="op in (item as any).options" :key="op.value" :label="op.label" :value="op.value" />
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
	</div>
</template>
<script lang="ts" setup>
import { FormInstance } from 'element-plus';

const props = defineProps({
	formRules: {
		type: Array,
		default: () => []
	},
	api: {
		type: Object,
		default: () => ({})
	},
	options: {
		type: Object,
		default: () => ({})
	}
});
const emit = defineEmits(['update:api']);
const formData = ref({ ...props.api });
const formInstance = ref<FormInstance>();

const rules = computed(() => {
	return props.formRules.filter(item => !item.hidden);
});
watch(
	() => formData.value,
	val => {
		emit('update:api', val);
	},
	{ deep: true }
);
defineExpose({
	validate() {
		return formInstance.value?.validate();
	},
	resetFields() {
		formInstance.value?.resetFields();
	},
	setValue(...args) {
		if (args.length === 2) {
			const [field, value] = args;
			formData.value[field] = value;
		} else {
			formData.value = args[0];
		}
		// formData.value[field] = value;
	},
	getValue(field) {
		return formData.value[field];
	}
});
</script>
